

import { AppDataSource } from '@/config/AppDataSource';
import { CreateTableInfoDto, UpdateTableInfoDto, QueryTableInfoDto, DeleteTableInfoDto, SelectOneTableInfoDto } from '@/dto/tableInfo.dto';
import { TableInfo } from '@/entities/tableInfo.entity';
import { FindOneOptions, In } from 'typeorm';
export class TableInfoRepository {
    private repositor = AppDataSource.getRepository(TableInfo);
    constructor() { }

    async findExcludeId(data: UpdateTableInfoDto) {
        const conflictCategory = await this.repositor
            .createQueryBuilder('tableInfo')
            .where('tableInfo.id != :id', { id: data.id })
            .andWhere('(tableInfo.name = :name)', { name: data.name })
            .getOne();
        return conflictCategory
    }


    async tableInfoExists(name: string) {
        const c = await this.repositor.findOne({
            where: [
                { name },
            ],
        });
        return c;
    }
    async findById(id: number) {

        const item = await this.repositor.findOne({
            where: { id },
        })
        return item;
    }
    async selectOne(reqData: SelectOneTableInfoDto) {
        const q: FindOneOptions<TableInfo> = {
            where: { id: reqData.id }
        }
        if (reqData.queryChildren) {
            q.relations = ['indexInfoList', 'fieldInfoList'],
                q.order = {
                    indexInfoList: { id: 'ASC' },
                    fieldInfoList: { id: 'ASC' }
                }
        }

        const item = await this.repositor.findOne(q)
        return item;
    }

    async create(data: CreateTableInfoDto): Promise<TableInfo> {
        const tableInfo = new TableInfo();

        tableInfo.status = data.status;
        tableInfo.comment = data.comment;
        tableInfo.name = data.name;

        const result = await this.repositor.save(tableInfo)
        // console.log("result", result)
        return result;
    }
    async update(data: UpdateTableInfoDto) {
        const tableInfo = new TableInfo();
        tableInfo.id = data.id;

        tableInfo.status = data.status;
        tableInfo.comment = data.comment;
        tableInfo.name = data.name!;

        return this.repositor.save(tableInfo);

    }



    async selectList(reqData: QueryTableInfoDto) {
        const { page, pageSize, name, orderBy, comment, status, fromDate, toDate } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('tableInfo')
            .select([

                'tableInfo.id',
                'tableInfo.createdAt',
                'tableInfo.updatedAt',
                'tableInfo.status',
                'tableInfo.comment',
                'tableInfo.name',
            ]);

        if (name) {
            queryBuilder.andWhere('tableInfo.name LIKE :name', { name: `%${name}%` });
        }
        if (comment) {
            queryBuilder.andWhere('tableInfo.comment LIKE :comment', { comment: `%${comment}%` });
        }
        if (status) {
            queryBuilder.andWhere('tableInfo.status = :status', { status });
        }
        // 添加创建日期范围查询
        if (fromDate && toDate) {
            queryBuilder.andWhere('tableInfo.createdAt BETWEEN :fromDate AND :toDate', {
                fromDate: new Date(fromDate),
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        } else if (fromDate) {
            queryBuilder.andWhere('tableInfo.createdAt >= :fromDate', {
                fromDate: new Date(fromDate)
            });
        } else if (toDate) {
            queryBuilder.andWhere('tableInfo.createdAt <= :toDate', {
                toDate: new Date(`${toDate}T23:59:59.999Z`)

            });
        }
        const [sortBy, sortOrder] = orderBy.split(" ")
        const [tableInfo, total] = await queryBuilder
            .orderBy(`tableInfo.${sortBy}`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
        return {
            list: tableInfo,
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: DeleteTableInfoDto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }

}

export default new TableInfoRepository();

